package com.cpx.controller;

import com.cpx.dto.MenuDto;
import com.cpx.feign.EmployeeFeign;
import com.cpx.po.Employee;
import com.cpx.vo.JsonResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collection;
import java.util.List;

/**
 * @Auther: PanBin
 * @Date: 2018-11-7 14:38
 * @Description: 首页的controller
 * @Version: 1.0
 */
@Api(value = "IndexController", tags = "首页管理")
@Controller
public class IndexController {

    private static Logger logger = LogManager.getLogger(IndexController.class);

    @Autowired
    private EmployeeFeign employeeFeign;
    @Autowired
    private SessionDAO sessionDAO;

    /**
     * @Author: PanBin
     * @Description: 跳转到首页
     * @CreateDate: 2018-11-8 14:42
     * @Param [model]
     * @Return java.lang.String
     */
    @ApiOperation(value = "首页")
    @RequestMapping(value = "/index",method = RequestMethod.GET)
    public String index(Model model) {
        Subject subject = SecurityUtils.getSubject();
        Employee employee = (Employee)subject.getPrincipal();//获取登录的用户
        employee.setPassword(null);
        model.addAttribute("loginEmployee",employee);
        List<MenuDto> menuList = employeeFeign.getMenuByEmployeeId(employee.getId());
        model.addAttribute("menuList",menuList);
        return "index";
    }

    /**
     * @Author: PanBin
     * @Description: 跳转到登录页面
     * @CreateDate: 2018-11-8 14:42
     * @Param []
     * @Return java.lang.String
     */
    @ApiOperation(value = "登录页面")
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login() {

        return "login";
    }

    /**
     * @Author: PanBin
     * @Description: 用户登录的方法
     * @CreateDate: 2018-9-5 15:20
     * @Param [username, password, session]
     * @Return java.lang.String
     */
    @ApiOperation(value = "员工登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名(Y)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "password", value = "密码(Y)", required = true, paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/confirmLogin", method = RequestMethod.POST)
    public @ResponseBody JsonResultVo confirmLogin(String username, String password) {
        JsonResultVo resultVo = new JsonResultVo();
        try {
            //重复登录，下线以前的登录
            Collection<Session> sessions = sessionDAO.getActiveSessions();
            for(Session session : sessions) {
                Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
                SimplePrincipalCollection spc = (SimplePrincipalCollection) obj;
                if (spc != null) {
                    Employee employee = (Employee) spc.getPrimaryPrincipal();
                    if (username.equals(employee.getUsername())) {
                        session.stop();
                    }
                }
            }
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
            Subject subject = SecurityUtils.getSubject();
            subject.login(usernamePasswordToken);   //完成登录
        } catch (AuthenticationException e) {
            resultVo.setErrMsg("用户名或者密码错误");
            logger.error("登录失败：",e);
            e.printStackTrace();
        }
        return resultVo;
    }

    /**
     * @Author: PanBin
     * @Description: 用户登出的方法
     * @CreateDate: 2018-9-5 15:20
     * @Param [session]
     * @Return java.lang.String
     */
    @ApiOperation(value = "退出登录")
    @RequestMapping(value = "/loginOut", method = RequestMethod.GET)
    public String logOut() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/manager/login.html";
    }

    /**
     * @Author: PanBin
     * @Description: 未授权页面
     * @CreateDate: 2018-11-9 12:11
     * @Param []
     * @Return java.lang.String
     */
    @ApiOperation(value = "未授权页面")
    @RequestMapping(value = "/notPerm", method = RequestMethod.GET)
    public String notPerms(){

        return "exception/notPerm";
    }

    /**
     * @Author: PanBin
     * @Description: 403页面
     * @CreateDate: 2018-11-9 12:11
     * @Param []
     * @Return java.lang.String
     */
    @ApiOperation(value = "403页面")
    @RequestMapping(value = "/403", method = RequestMethod.GET)
    public String page403(){

        return "exception/403";
    }

    /**
     * @Author: PanBin
     * @Description: 404页面
     * @CreateDate: 2018-11-9 12:12
     * @Param []
     * @Return java.lang.String
     */
    @ApiOperation(value = "404页面")
    @RequestMapping(value = "/404", method = RequestMethod.GET)
    public String page404(){

        return "exception/404";
    }

    /**
     * @Author: PanBin
     * @Description: 500页面
     * @CreateDate: 2018-11-9 12:12
     * @Param []
     * @Return java.lang.String
     */
    @ApiOperation(value = "500页面")
    @RequestMapping(value = "/500", method = RequestMethod.GET)
    public String page500(){

        return "exception/500";
    }
}
